<template>
  <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
    <el-row>
      <!-- 按钮名称 -->
      <el-col
        v-for="item in formJson.components"
        :key="item.id"
        :span="item.spanValue"
      >
        <el-form-item
          v-if="isFormVisible(item)"
          :label="item.label"
          :prop="item.id"
        >
          <el-select
            v-if="item.type === 'select'"
            v-model="form[item.id]"
            :placeholder="item.placeholder"
            :disabled="item.disabled || item.readonly"
            @change="handleFormChange"
          >
            <el-option
              v-for="i in item.values"
              :key="i.value"
              :label="i.label"
              :value="i.value"
            />
          </el-select>
          <el-input
            v-if="item.type === 'textfield'"
            v-model="form[item.id]"
            :placeholder="item.placeholder"
            :disabled="item.disabled || item.readonly"
            @input="handleFormChange"
          />
          <el-input
            v-if="item.type === 'textarea'"
            v-model="form[item.id]"
            :rows="2"
            type="textarea"
            :placeholder="item.placeholder"
            :disabled="item.disabled || item.readonly"
            @input="handleFormChange"
          />
          <el-input-number
            v-if="item.type === 'number'"
            v-model="form[item.id]"
            controls-position="right"
            :disabled="item.disabled || item.readonly"
            :placeholder="item.placeholder"
            :precision="2"
            class="w-full"
            @change="handleFormChange"
          />
          <template v-if="item.type === 'filepicker'">
            <el-button
              v-if="!item.readonly"
              type="primary"
              :icon="Upload"
              @click="handleUploadFiles(item.id)"
            >
              {{ $t("common.uploadFiles") }}
            </el-button>
            <div v-if="!item.readonly" style="flex-basis: 100%">
              <div
                v-for="(i, index) in form[item.id]"
                :key="index"
                class="files-list"
              >
                {{ i.fileName }}
                <el-icon
                  size="16"
                  class="icon-right"
                  @click="handleDeleteFiles(index, item.id)"
                >
                  <CircleClose />
                </el-icon>
              </div>
            </div>
            <div v-if="item.readonly" class="file-download">
              <div
                v-for="file in form[item.id]"
                :key="file.fileId"
                class="file-download-box"
              >
                <div class="box-files-left">
                  <img
                    v-if="hasFileIcon(file)"
                    :src="getFileIcon(file)"
                    alt=""
                    class="file_img"
                  />

                  <div class="file_left">
                    <span class="file_title">{{ file.fileName }}</span>
                    <span class="file_des"
                      >{{
                        (file.fileSize / 1024 / 1024).toFixed(1) || 0
                      }}M</span
                    >
                  </div>
                </div>
                <span
                  class="down-load"
                  @click="handlePreview({ filePath: file.fileSrc })"
                  >点击下载</span
                >
              </div>
            </div>
          </template>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  <jmash-multi-upload
    ref="uploadRef"
    v-model="uploadVisible"
    :limit="100"
    @upload-file-list="getFileList"
  />
</template>
<script setup lang="ts">
import { type PropType, reactive, ref } from "vue";
import { type FormRules, type FormInstance } from "element-plus";
import { Upload } from "@element-plus/icons-vue";
import { handlePreview } from "jmash-core";
import { hasFileIcon, getFileIcon } from "@/util/fileutil";
import { formDataApi, formFileApi } from "xyvcard-workflow";
import type { FlowTaskModel } from "@/api/flow/task/types";
const formRef = ref<FormInstance>();
// 表单数据
let form = reactive<any>({});
const props = defineProps({
  formJson: {
    type: Object,
    default: () => {},
  },
  task: {
    type: Object as PropType<FlowTaskModel>,
    default: () => {},
  },
});
console.log(props.formJson);
const rules = reactive<FormRules>({});
const activeField = ref<string>("");
const uploadVisible = ref<boolean>(false);
const uploadRef = ref(); // 上传组件
const emits = defineEmits(["form-change"]);

/**
 * 生成规则函数
 * @returns {Array} 返回一个包含规则的数组，每个规则对象包含验证条件和错误提示信息。
 */
function generateRules() {
  const rowMap = new Map<string, number>();
  props.formJson.components.forEach((item: any) => {
    // 必填项
    if (item.validate.required) {
      rules[item.id] = [
        {
          required: true,
          message: `${item.validate.validationType}` || `${item.label}不能为空`,
          trigger: ["change", "blur"],
        },
      ];
    }
    // 动态初始化文件字段（如果不存在则创建空数组）
    if (item.type === "filepicker") {
      if (!form[item.id]) {
        form[item.id] = [];
      }
    }
  });

  console.log(props.formJson.components);
}

function calculateRowSpans() {
  const rowMap = new Map<string, number>();

  // 先统计每个 row 的组件数量
  props.formJson.components.forEach((item: any) => {
    if (item.layout?.row) {
      const count = rowMap.get(item.layout.row) || 0;
      rowMap.set(item.layout.row, count + 1);
    }
  });

  // 再统一分配 span 值
  props.formJson.components.forEach((item: any) => {
    if (item.layout?.row) {
      const count = rowMap.get(item.layout.row) || 1;
      item.spanValue = Math.floor(24 / count);
    } else {
      item.spanValue = 24; // 默认全宽
    }
  });
}
// 获取表单数据
function findFormDataIn() {
  formDataApi
    .findById({
      formId: props.task.formKey,
      businessKey: props.task.businessKey,
    })
    .then(({ data }) => {
      Object.assign(form, data.data);
    });
}

/**
 * 判断表单项是否可见
 * @param {any} item - 表单项对象，包含以下属性：
 *   - hidden: boolean - 表示该表单项是否隐藏
 *   - readonly: boolean - 表示该表单项是否只读
 *   - id: string - 表单项的唯一标识符，用于在表单中查找对应的值
 *
 * @returns {boolean} - 返回一个布尔值，表示该表单项是否可见
 */
function isFormVisible(item: any) {
  // 如果是filepicker类型，则必须满足有文件的条件
  if (item.type === "filepicker") {
    return (
      (Boolean(form[item.id]) && form[item.id].length > 0) || !item.readonly
    );
  }
  return (
    (!item.hidden &&
      ((Boolean(form[item.id]) && !item.readonly) ||
        (Boolean(form[item.id]) && item.readonly))) ||
    !item.readonly
  );
}

function validate(callback: any) {
  //这个form是子组件内部 el-form 的 ref="contentForm"
  formRef.value?.validate((valid) => {
    callback(valid);
  });
}

// 上传相关评选文件
function handleUploadFiles(fieldId: string) {
  activeField.value = fieldId;
  console.log(activeField.value);
  uploadVisible.value = true;
  uploadRef.value.clearFileList();
}

// 获取相关评选文件列表
function getFileList(file: any) {
  console.log(file, form[activeField.value]);
  if (!activeField.value) return;
  const obj = {
    fileName: file.name,
    fileId: file.response.fileId,
  };
  form[activeField.value]?.push(obj);
  console.log(form[activeField.value]);
  form[activeField.value] = [...new Set(form[activeField.value])];
  console.log(form[activeField.value]);
  emits("form-change", form);
}

// 删除相关评选文件
function handleDeleteFiles(index: number, fieldId: string) {
  activeField.value = fieldId; // 确保 activeField 的值是当前操作的字段 ID
  if (!activeField.value) {
    console.error("activeField is undefined");
    return;
  }
  console.log(index, form[activeField.value]);
  form[activeField.value]?.splice(index, 1);
  emits("form-change", form);
}

function handleFormChange() {
  emits("form-change", form);
}

// 获取附件
function queryFileList() {
  formFileApi
    .findList({ actionId: props.task.businessKey })
    .then(({ data }) => {
      const components = props.formJson?.components || [];
      const fileMap = new Map();

      // 预先构建文件映射
      data.results.forEach((file: any) => {
        if (!fileMap.has(file.fileSort)) {
          fileMap.set(file.fileSort, []);
        }
        fileMap.get(file.fileSort).push(file);
      });

      // 填充 form 对象
      components.forEach((component: any) => {
        const files = fileMap.get(component.id) || [];
        if (files.length > 0) {
          form[component.id] = files;
        }
      });

      // 生产环境中应移除或替换为合适的日志记录方式
      console.log(form);
    });
}

queryFileList();

findFormDataIn();

generateRules();

calculateRowSpans();

defineExpose({
  validate,
});
</script>
<style lang="scss" scoped>
.file-download {
  background-color: #f6f6f6;
  padding: 5px 4%;
  border-radius: 5px;
  width: 100%;
  .file-download-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }
  .box-files-left {
    display: flex;
    align-items: center;
    width: 70%;
  }
  .down-load {
    color: #0551ff;
    font-size: 14px;
    cursor: pointer;
  }
  .file_left {
    display: flex;
    flex-direction: column;
    overflow: hidden;
    .file_title {
      color: #333;
      font-size: 14px;
      font-weight: bold;
      white-space: nowrap; /* 不换行 */
      overflow: hidden; /* 隐藏超出的内容 */
      text-overflow: ellipsis; /* 用省略号表示被隐藏的部分 */
    }
    .file_des {
      color: #666;
      font-size: 13px;
    }
  }
}

.files-list {
  display: flex;
  align-items: center;
  width: 100%;

  .icon-right {
    margin-left: auto;
  }
}

.file_img {
  width: 35px;
  margin-right: 8px;
}
</style>
